/*
  学习目标：实现退出登录
  步骤：
    0. 二次确认弹出框
     1. 删token
     2. 提示用户
     3. 返回登录页面

*/

import NavBar from "@/components/NavBar";
import { useAppDispatch, useAppSelector } from "@/store";
import {
  getProfileAction,
  updatePhotoAction,
  updateProfileActon,
} from "@/store/action/user";
import { Dialog, List } from "antd-mobile";
import { useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { Popup } from "antd-mobile";
import { Toast } from "antd-mobile";
import Input from "@/components/Input";
import TextArea from "@/components/TextArea";
import { DatePicker } from "antd-mobile";
import dayjs from "dayjs";
import { removeAuth } from "@/utils/storage";
import history from "@/utils/history";

type EditType = "photo" | "gender" | "name" | "intro";

export default function ProfileEdit() {
  const dispatch = useAppDispatch();
  useEffect(() => {
    dispatch(getProfileAction());
  }, [dispatch]);
  const { profile } = useAppSelector((state) => state.user);

  const [editType, setEditType] = useState("" as EditType);

  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [birthVisible, setBirthVisible] = useState(false);

  const [name, setName] = useState("");
  const [intro, setIntro] = useState("");

  useEffect(() => {
    if (profile.name) setName(profile.name);
    if (profile.intro) setIntro(profile.intro);
  }, [profile]);

  const iptRef = useRef<HTMLInputElement>(null);

  const handleShowUpload = () => {
    iptRef.current?.click();
  };

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files?.length) {
      const formData = new FormData();
      formData.append("photo", e.target.files[0]);
      await dispatch(updatePhotoAction(formData));

      handleRefresh();
    }
  };

  const handleRefresh = () => {
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
    dispatch(getProfileAction());
    Toast.show("更新成功");
  };

  const handleShowPopup = (type: EditType) => {
    setEditType(type);
    if (type === "gender" || type === "photo") setVisible(true);
    if (type === "name" || type === "intro") setRightVisible(true);
  };

  const handleUpdateProfile = async (profile: Partial<IProfile>) => {
    await dispatch(updateProfileActon(profile));
    handleRefresh();
  };

  const renderPhotoAndGender = () => {
    if (editType === "photo") {
      return (
        <>
          <div className="list-item" onClick={handleShowUpload}>
            拍照
          </div>
          <div className="list-item" onClick={handleShowUpload}>
            本地选择
          </div>
        </>
      );
    }
    if (editType === "gender") {
      return (
        <>
          <div
            onClick={() => handleUpdateProfile({ gender: 0 })}
            className="list-item"
          >
            男
          </div>
          <div
            onClick={() => handleUpdateProfile({ gender: 1 })}
            className="list-item"
          >
            女
          </div>
        </>
      );
    }
  };

  const handleBack = () => {
    setRightVisible(false);
    if (editType === "name") setName(profile.name);

    if (editType === "intro") setIntro(profile.intro || "");
  };

  const renderNameAndIntro = () => {
    const params: Partial<IProfile> = {};

    if (editType === "name") params.name = name;
    if (editType === "intro") params.intro = intro;
    return (
      <>
        <NavBar
          onBack={handleBack}
          right={
            <span
              className="submit-btn"
              onClick={() => handleUpdateProfile(params)}
            >
              提交
            </span>
          }
        >
          {editType === "intro" && "编辑简介"}
          {editType === "name" && "编辑昵称"}
        </NavBar>
        <div className="edit-content">
          {editType === "name" && (
            <Input
              className="edit-input"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          )}
          {editType === "intro" && (
            <TextArea
              value={intro}
              onChange={(e) => setIntro(e.target.value)}
            />
          )}
        </div>
      </>
    );
  };

  const handleLoginOut = () => {
    Dialog.confirm({
      title: "温馨提示",
      content: "确定退出吗",
      onConfirm() {
        removeAuth();
        history.push("/login");
        Toast.show("退出成功");
      },
    });
  };

  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              onClick={() => handleShowPopup("photo")}
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
            >
              头像
            </List.Item>

            <List.Item
              onClick={() => handleShowPopup("name")}
              arrow
              extra={profile.name}
            >
              昵称
            </List.Item>

            <List.Item
              onClick={() => handleShowPopup("intro")}
              arrow
              extra={<span className="intro">{profile.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item
              onClick={() => handleShowPopup("gender")}
              arrow
              extra={profile.gender === 0 ? "男" : "女"}
            >
              性别
            </List.Item>
            <List.Item
              onClick={() => setBirthVisible(true)}
              arrow
              extra={profile.birthday}
            >
              生日
            </List.Item>
          </List>

          <input
            onChange={handleUpload}
            ref={iptRef}
            className="avatar-upload"
            type="file"
          />
        </div>

        <div className="logout">
          <button onClick={handleLoginOut} className="btn">
            退出登录
          </button>
        </div>
      </div>

      <Popup visible={visible} bodyClassName="popup-bottom-list">
        {renderPhotoAndGender()}
        <div className="list-item" onClick={() => setVisible(false)}>
          取消
        </div>
      </Popup>
      <Popup
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
        destroyOnClose
      >
        {renderNameAndIntro()}
      </Popup>
      <DatePicker
        visible={birthVisible}
        title="选择生日"
        onClose={() => setBirthVisible(false)}
        min={new Date("1900-01-01")}
        max={new Date()}
        onConfirm={(val) => {
          dispatch(
            handleUpdateProfile({ birthday: dayjs(val).format("YYYY-MM-DD") })
          );
        }}
      />
    </div>
  );
}
